package com.ins1st.util;

import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

@SuppressWarnings({ "rawtypes", "unchecked" })
public class QueryUtil {

	public static IPage getPage(HttpServletRequest request) {
		String page = StringUtils.defaultIfBlank(request.getParameter("page"), "1");
		String limit = StringUtils.defaultIfBlank(request.getParameter("limit"), "10");
		return new Page<>(Integer.parseInt(page), Integer.parseInt(limit));
	}
	
	public static QueryWrapper build(HttpServletRequest request) {
		QueryWrapper query = new QueryWrapper();
		Map<String, String[]> map = request.getParameterMap();
		Set<String> keys = map.keySet();
		for (String key : keys) {
			if (!key.startsWith("Q_"))
				continue;

			String param = key.substring(2);
			String[] arr = StringUtils.split(param, "_");
			String matchType = arr[0];

			// SQL的参数都可以传字符串
			if (matchType.equals("LIKE")) {
				query.like(arr[1], map.get(key)[0]);
			} else if (matchType.equals("EQ")) {
				query.eq(arr[1], map.get(key)[0]);
			} else if (matchType.equals("NEQ")) {
				query.ne(arr[1], map.get(key)[0]);
			} else if (matchType.equals("GT")) {
				query.gt(arr[1], map.get(key)[0]);
			} else if (matchType.equals("GE")) {
				query.ge(arr[1], map.get(key)[0]);
			} else if (matchType.equals("LT")) {
				query.lt(arr[1], map.get(key)[0]);
			} else if (matchType.equals("LE")) {
				query.le(arr[1], map.get(key)[0]);
			}
		}

		return query;
	}

}
